/* eslint-disable @typescript-eslint/no-empty-object-type */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createSlice, PayloadAction } from "@reduxjs/toolkit";

// 定义菜单项的类型
interface MenuItem {
  path: string;
  name: string;
  label: string;
}

// 定义 Slice 的状态类型
interface TabState {
  collapsed: boolean;
  tabList: MenuItem[];
  currentMenu: MenuItem | {};
}

// 创建 Slice
const tabSlice = createSlice({
  name: "tab",
  initialState: {
    collapsed: false,
    tabList: [
      {
        path: "/",
        name: "home",
        label: "首页",
      },
    ],
    currentMenu: {},
  } as TabState,
  reducers: {
    setCollapsed: (state: { collapsed: boolean }) => {
      state.collapsed = !state.collapsed;
    },
    selectMenuList: (
      state: { currentMenu: {}; tabList: any[] },
      action: PayloadAction<MenuItem>
    ) => {
      const val = action.payload;
      if (val.name !== "home") {
        state.currentMenu = val;
        const result = state.tabList.findIndex(
          (item: { name: any }) => item.name === val.name
        );
        if (result === -1) {
          state.tabList.push(val);
          console.log(state.tabList, "selectMenuList");
        }
      } else {
        state.currentMenu = {};
      }
    },
    closeTag: (state: { tabList: any[] }, action: PayloadAction<MenuItem>) => {
      const val = action.payload;
      const res = state.tabList.findIndex(
        (item: { name: any }) => item.name === val.name
      );
      if (res !== -1) {
        state.tabList.splice(res, 1);
      }
    },
    setCurrentMenu: (
      state: { currentMenu: {} },
      action: PayloadAction<MenuItem>
    ) => {
      const val = action.payload;
      if (val.name === "home") {
        state.currentMenu = {};
      } else {
        state.currentMenu = val;
      }
    },
  },
});

export default tabSlice.reducer;

// 导出 actions
export const { setCollapsed, selectMenuList, closeTag, setCurrentMenu } =
  tabSlice.actions;
